// 控制端渲染进程页面

import { ipcRenderer, remote } from "electron";
import React, { useState, useEffect } from "react";
import "./App.css";
import "./peer-puppet.js";

const { Menu, MenuItem } = remote;

function App() {
  const [remoteCode, setRemoteCode] = useState("");
  const [localCode, setLocalCode] = useState("");
  const [controlText, setControlText] = useState("");

  // 登录获取并设置本机控制码
  const login = async () => {
    let code = await ipcRenderer.invoke("login");
    setLocalCode(code);
  };

  useEffect(() => {
    // 启动程序开始登录
    login();
    // 监听控制状态的变化，触发处理状态的事件
    ipcRenderer.on("control-state-change", handleControlState);

    return () => {
      // 程序销毁移除监听事件
      ipcRenderer.removeListener("control-state-change", handleControlState);
    };
  }, []);

  // 开始控制，发送远程控制码给主进程处理
  const startControl = (remoteCode) => {
    ipcRenderer.send("control", remoteCode);
  };

  // 处理控制状态
  const handleControlState = (e, name, type) => {
    let text = "";
    if (type === 1) {
      // 控制别人
      text = `正在远程控制${name}`;
    } else if (type === 2) {
      // 被控制
      text = `被${name}控制中`;
    }
    setControlText(text);
  };

  const handleCopy = (e) => {
    e.preventDefault();
    const menu = new Menu();
    menu.append(new MenuItem({ label: "复制", role: "copy" }));
    menu.popup();
  };
  const handlePaste = (e) => {
    e.preventDefault();
    const menu = new Menu();
    menu.append(new MenuItem({ label: "粘贴", role: "paste" }));
    menu.popup();
  };

  return (
    <div className="App">
      {controlText === "" ? (
        <>
          <div>
            你的控制码
            <span onContextMenu={(e) => handleCopy(e)}>{localCode}</span>
          </div>
          <input
            type="text"
            value={remoteCode}
            onChange={(e) => setRemoteCode(e.target.value)}
            onContextMenu={(e) => handlePaste(e)}
          />
          <button onClick={() => startControl(remoteCode)}>确认</button>
        </>
      ) : (
        <div>{controlText}</div>
      )}
    </div>
  );
}

export default App;
